<?php

namespace App\Http\Controllers\API\Systems;

use DB;
use Config;
use Hash;
use App\Http\Controllers\API\ApiController;
use Ramsey\Uuid\Uuid;
use Illuminate\Http\Request;
use App\Eloqumd\System\Plate;
use App\Eloqumd\System\PlateUser;
use App\Validate\System\SystemValidator;

class PlateController extends ApiController
{
    // 获取平台列表
    public function getPlatformList(Request $request)
    {
        $page = (int)$request->input('page/d', 1) - 1;
        $limit = $request->input('limit/d', $this->limit);
        $keyword = $request->input('keyword', '');

        $where = null;
        // 快捷搜索
        if ($keyword) {
            $where[] = ['plate_code', 'like', "%{$keyword}%", 'OR'];
            $where[] = ['plate_name', 'like', "%{$keyword}%", 'OR'];
        }

        $totalCount = Plate::where($where)->count();
        $listData = Plate::where($where)
            ->offset($page)
            ->limit($limit)
            ->get()
            ->toArray();

        foreach ($listData as $k => $v) {
            $listData[$k]['admin_name'] = PlateUser::where('user_type', 1)->where('user_plate', $v['plate_code'])->value('user_name');
        }

        $jsonData = ['list' => $listData, 'count' => $totalCount];

        return $this->jsonReturns(10000, $this->success, $jsonData, 'list', trans('alg.Browse-Platform-List-Info'));
    }

    // 根据平台ID获取平台信息
    public function getPlatformInfoById(Request $request)
    {
        $plateId = $request->input('id', 0);
        $plateInfo = Plate::find($plateId);

        return $this->jsonReturns(
            10000,
            $this->success,
            $plateInfo,
            'get',
            trans('alg.Get-Browse-Platform-Info', ['name' => $plateInfo['plate_name'], 'id' => $id])
        );
    }

    // 添加平台
    public function platformCreated(Request $request)
    {
        // 数据校验
        $param = $request->all();
        if (true !== $validateRes = SystemValidator::platformCreated($param)) {
            return $this->jsonReturns(99999, $validateRes, [], 'create/verror', trans('alg.Create-Platform-And-Validate-Error'));
        }

        // 数据处理
        DB::beginTransaction();
        try {
            $model = new Plate;
            $model->plate_name = $param['plate_name'];
            $model->plate_desc = $param['plate_desc'] ?? '';
            $model->plate_status = $param['plate_status'] ?? 0;
            $model->plate_created_at = date('Y-m-d H:i:s');
            $model->plate_code = strtoupper($param['plate_code']);
            $model->plate_secret = Uuid::uuid1()->getHex();
            $model->save();

            // 同步创建admin平台管理员用户信息
            $pus = new PlateUser;
            $pus->user_plate = $model->plate_code;
            $pus->user_name = $model->plate_code . mt_rand(1000, 9999);
            $initPwd = Config::get('api.init_system_pwd');
            $userSolt = Uuid::uuid1()->getHex();
            $pus->user_solt = $userSolt;
            $pus->user_pass = Hash::make($initPwd, ['solt' => $userSolt]);
            $pus->user_real_name = $model->plate_name . substr(Uuid::uuid1()->getHex(), 0,4);
            $pus->user_type = 1;
            $pus->user_status = 1;
            $pus->created_at = date('Y-m-d H:i:s');
            $pus->save();

            DB::commit();

            return $this->jsonReturns(
                10000,
                $this->success,
                [],
                'create',
                trans('alg.Create-Platform-Info-And-Create-Platform-Admin-User', [
                    'name' => $param['plate_name'],
                    'admin' => $pus->user_name,
                ])
            );
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), [], 'create/error', trans('alg.Create-Platform-System-Error'));
        }
    }

    // 修改平台
    public function platformModified(Request $request)
    {
        // 数据校验
        $param = $request->all();
        if (true !== $validateRes = SystemValidator::platformModified($param)) {
            return $this->jsonReturns(99999, $validateRes, [], 'modify/verror', trans('alg.Modify-Platform-And-Validate-Error'));
        }

        // 数据处理
        DB::beginTransaction();
        try {
            $model = Plate::find($param['id']);
            $model->plate_name = $param['plate_name'];
            $model->plate_desc = $param['plate_desc'] ?? '';
            $model->plate_status = $param['plate_status'] ?? 0;
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success, [], 'modify', trans('alg.Modify-Platform-Success', ['name' => $param['plate_name']]));
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), [], 'modfiy/error', trans('alg.Modify-Platform-System-Error'));
        }
    }

    // 启用禁用平台-单个
    public function platformStatused(Request $request)
    {
        // 数据校验
        $id = $request->input('id', 0);
        $plate_status = $request->input('plate_status', '');
        if (!$id || $plate_status == '') {
            return $this->jsonReturns(99999, trans('alg.Illegal-Parameter', ['p' => 'id/plate_status']), [], 'status/error', trans('alg.Status-Platform-And-Validate-Error'));
        }

        // 数据处理
        DB::beginTransaction();
        try {
            $model = Plate::find($id);
            $model->plate_status = $plate_status;
            $model->save();

            DB::commit();

            return $this->jsonReturns(
                10000,
                $this->success,
                [],
                'status',
                trans('alg.Status-Platform-Success', [
                    'name' => $model->plate_name,
                    'status' => ($plate_status == 1 ? trans('alg.Enabled') : trans('alg.Disabled'))
                ])
            );
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), [], 'status/error', trans('alg.Status-Platform-System-Error'));
        }
    }
}
